package com.idbk.chargestation.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.bean.JsonReplyResult;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;

/**
 * 回复评论输入Dialog<br/>
 * <ll>
 * <li>对象是评论本身，如果是评论人自己，则显示为 评论；如果是其他人，则显示为 回复 XXX：</li>
 * <li>对象是评论回复，如果该回复是自己发的，则显示为  XXX：，如果是其他人，则显示为 </li>
 * </ll>
 *
 * @author liangzw, lupc
 */
public class DialogReplyComment extends Dialog implements OnClickListener,
        TextWatcher {

    private Context context;
    private EditText editInput;//回复信息输入
    private TextView mTextSend;//信息发送

    private String mCommentUserName;//该评论用户名
    private int mCommentUserId, mCommentId;

    /**
     * 标志，true表示该回复 是针对 评论本身，false表示针对 评论的回复
     */
    private boolean mIsToComment = true;

    private OnReplaySuccessListener mOnReplySuccessListener;

    public DialogReplyComment(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//设置无标题
        if (getWindow() != null) {
            //设置对话框背景无黑色,无模糊
            getWindow().clearFlags(LayoutParams.FLAG_BLUR_BEHIND | LayoutParams.FLAG_DIM_BEHIND);
            //设置dialog默认背景为透明
            getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            getWindow().setGravity(Gravity.BOTTOM);//设置Dialog显示在下方
            //设置输入法自动弹出
            getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            View mView = inflater.inflate(R.layout.dialog_reply_comment, null);//找到布局
            setContentView(mView);
            //设置Dialog横向全屏,纵向匹配内容
            getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        }

        setupView();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.dismiss();
        return super.onTouchEvent(event);
    }

    private void setupView() {
        editInput = (EditText) findViewById(R.id.dialog_reply_edit);
        editInput.addTextChangedListener(this);

        mTextSend = (TextView) findViewById(R.id.textview_send);
        mTextSend.setOnClickListener(this);
        mTextSend.setBackgroundResource(R.drawable.tj_coners_button_gray);

        //EditText获取焦点
        editInput.setFocusable(true);
        editInput.requestFocus();
    }

    public void setOnReplaySuccessListener(OnReplaySuccessListener o) {
        mOnReplySuccessListener = o;
    }

    @Override
    public void show() {
        super.show();
        //如果评论是自己发的，则显示“评论”，否则显示“回复 XXX”
        int userId = AppContext.getInstance().getMyUserId();
        if (userId == mCommentUserId) {
            editInput.setHint("评论");
        } else {
            editInput.setHint("回复:" + mCommentUserName);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //当无输入信息时
        if (editInput.getText().toString().equals("")) {
            mTextSend.setBackgroundResource(R.drawable.tj_coners_button_gray);
            mTextSend.setEnabled(false);
        } else {
            mTextSend.setBackgroundResource(R.drawable.tj_coners_button_theme);
            mTextSend.setEnabled(true);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview_send:
                reply();//回复
                break;
            default:
                break;
        }
    }

    private void reply() {
        if (editInput.getText().toString().equals("")) {
            return;
        }
        this.dismiss();
        final String comment = editInput.getText().toString();
        //请求回复
        ChargeStationAPI.replyComment(
                mCommentUserId,
                comment,
                mCommentId,
                mIsToComment,
                mResponse);
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonReplyResult result = GsonUtils.toBean(JsonReplyResult.class, response);
            if (result.status == GlobalResult.OK.getStatus()) {
                editInput.setText("");
                Toast.makeText(context, "回复成功", Toast.LENGTH_SHORT).show();
                //刷新数据
                if (mOnReplySuccessListener != null) {
                    mOnReplySuccessListener.onReplay(result);
                }
            } else {
                Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Toast.makeText(
                    context,
                    R.string.common_tip_resultfail,
                    Toast.LENGTH_SHORT)
                    .show();
        }

    };

    //	/**
//	 *
//	 * @param commentId
//	 * @param toReplyUserId
//	 * @param toReplyUserName
//	 * @param isToComment 标志，true表示该回复 是针对 评论本身，false表示针对 评论的回复
//	 */
    public void setReplyToComment(
            int commentId,
            int toReplyUserId,
            String toReplyUserName,
            boolean isToComment) {
        mCommentId = commentId;
        mCommentUserId = toReplyUserId;
        mCommentUserName = toReplyUserName;
        mIsToComment = isToComment;
    }

    public interface OnReplaySuccessListener {
        void onReplay(JsonReplyResult result);
    }

}
